<template>
  <div id="confirm-order-more-page">
    <div class="page-title" :style="{top:(this.getSafeArea().top-4)+'px'}">
      <div id="back-button" @click="$router.push('/')">
        <i class="el-icon-arrow-left"></i>
      </div>
      <span>订单确认</span>
    </div>
    <div style="position: relative; overflow-y: auto;overflow-x: hidden;padding-bottom: 55px; background: #f1f1f1;"
         :style="{
      top:(this.getSafeArea().top+30)+'px',
      height:(this.getWinSize().height-this.getSafeArea().top-50)+'px'
    }">

      <div class="address-box address-box-more" v-show="needAddress" style="position: relative;" :style="{
        top:'10px',
      }">

        <!--      <div class="title-bar">地址信息</div>-->
        <address-item v-if="isGetAddress" :addressData="memberAddress" :show-type="1" from="ConfirmOrderMore"/>
        <div class="bottom-bar"></div>
<!--        <div class="address-box-mask" v-if="userAddress && userAddress.id>0">-->
<!--          {{ sameCityErrorInfo }}-->
<!--        </div>-->
      </div>

      <div id="confirm-order-more-page-shop-list" v-if="isGetShopList">
        <confirm-order-more-shop-item
          ref="confirm-order-more-shop-item"
          v-for="(shop,index) in selectShopList"
          :curr-member-address="memberAddress"
          :curr-member="userInfo"
          :level-map="levelMap"
          :select-data="shop"
          :key="index"
          :check-need-address="checkNeedAddress"
          :get-coupon-list="getAbleCouponList"
          :call-back-calc-product-money="calcAllPrice"
          :set-coupon="setCouponUsed"/>
        <div class="c"></div>
      </div>

      <div class="product-price-detail product-price-detail-more">
        <div class="title">
          <span>
            金额明细
          </span>
        </div>
        <div class="item">
          <div class="left">商品金额:</div>
          <div class="right">
            <span v-text="ToMoney(priceDetail.productPrice)"></span>
          </div>
        </div>
        <div class="item" v-if="priceDetail.expressPrice>0">
          <div class="left">配送费:</div>
          <div class="right b red" v-text="ToMoney(priceDetail.expressPrice)"></div>
        </div>
        <div class="item">
          <div class="left">优惠券:
          </div>
          <div class="right">
            <span v-if="priceDetail.couponPrice>0" v-text="'-'+ToMoney(priceDetail.couponPrice)"></span>
            <span v-if="priceDetail.couponPrice===0">-</span>
          </div>
        </div>
        <div class="item">
          <div class="left">店铺满减:</div>
          <div class="right">
            <span v-if="priceDetail.fullMinusPrice>0" v-text="'-'+ToMoney(priceDetail.fullMinusPrice)"></span>
          </div>
        </div>
        <div class="item" v-if="priceDetail.vipDiscountPrice>0">
          <div class="left">会员优惠:
            <el-tag type="success" v-text="levelMap[userInfo.level].name"></el-tag>
            <el-tag type="warning" v-text="'折扣: '+(((1-userInfo.vipDiscount).toFixed(2)-0)*100).toFixed(0)+'%'" v-if="userInfo.vipDiscount>0"></el-tag>
          </div>
          <div class="right">
            <span class="red" v-text="'-'+ToMoney(priceDetail.vipDiscountPrice)"></span>
          </div>
        </div>
        <div class="item">
          <div class="left">合计:</div>
          <div class="right">
            <span class="red" v-text="'￥'+ToMoney(priceDetail.price)"></span>
          </div>
        </div>
        <div class="item" v-if="score>0">
          <div class="left">所需积分:
            <span class="b red" v-text="score"></span>
          </div>
          <div class="right">
            <div class="tip-box account-score-box">
              当前账户<span v-text="userInfo.score"></span>
            </div>
          </div>
        </div>
        <!--      <div class="item">-->
        <!--        <div class="left">店铺特殊优惠: </div>-->
        <!--        <div class="right" v-text="ToMoney(currCoupon.price)"></div>-->
        <!--      </div>-->
      </div>

      <div class="pay-choose-box">
        <div class="title">支付方式</div>
        <div class="item" @click="payType=0">
          <div class="left">
            <div class="icon money-pay"></div>
            <span>余额支付</span>
            <span class="red b" v-text="'￥'+ToMoney(userInfo.money)"></span>
          </div>
          <div class="right">
            <div class="pay-choose-icon" :class="payType===0?'on':''"></div>
          </div>
        </div>
<!--        <div class="item" @click="payType=1">
          <div class="left">
            <div class="icon wechat-pay"></div>
            <span>微信</span>
          </div>
          <div class="right">
            <div class="pay-choose-icon" :class="payType===1?'on':''"></div>
          </div>
        </div>
        <div class="item" @click="payType=2">
          <div class="left">
            <div class="icon ali-pay"></div>
            <span>支付宝</span>
          </div>
          <div class="right">
            <div class="pay-choose-icon" :class="payType===2?'on':''"></div>
          </div>
        </div>
        <div class="item" @click="payType=3">
          <div class="left">
            <div class="icon enterprise-pay"></div>
            <span>对公支付</span>
          </div>
          <div class="right">
            <div class="pay-choose-icon" :class="payType===3?'on':''"></div>
          </div>
        </div>-->
      </div>
    </div>
    <div id="confirm-order-more-page-bottom">
      <div class="left" >
        <div class="row">共 <span class="b" v-text="priceDetail.productNums"></span> 件,
          合计 <span style="font-size: 14px; color: #ab1616; font-weight: bold" v-text="'￥'+ToMoney(priceDetail.price)"></span>元</div>
        <div class="row">共减 <span style="font-size: 14px; color: #ab1616; font-weight: bold" v-text="ToMoney((priceDetail.fullMinusPrice+(priceDetail.couponPrice?priceDetail.couponPrice:0)+priceDetail.vipDiscountPrice).toFixed(2)-0)"></span>元</div>
      </div>
      <div class="right">
        <el-button type="danger" size="medium" @click="submit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import ConfirmOrderMoreShopItem from "../common/ConfirmOrderMoreShopItem";
import AddressItem from "../common/AddressItem";
export default {
  name: "ConfirmOrderMore",
  components: {AddressItem, ConfirmOrderMoreShopItem},
  data:function () {
    return {
      isInit:false,
      loading:false,
      selectShopList:[],
      couponList:[],
      classifyIdMapList:[],
      payType:0,
      priceDetail:{
        productPrice:0,
        couponPrice:0,
        expressPrice:0,
        fullMinusPrice:0,
        vipDiscountPrice:0,
        price:0,
      },
      //
      score:0,
      // 是否需要用户地址
      needAddress:true,
      isGetAddress:false,
      // 当前用户所选地址
      memberAddress:{
        id:0
      },
      levelMap:{},
      // 用户信息
      userInfo:{
        money:0,
        score:0,
      },
      isGetShopList:false
    }
  },
  mounted() {
    let $this=this
    this.initData(function () {
      setTimeout(function () {
        $this.calcAllPrice()
      },1000)
    })
  },
  methods:{
    // 获取-默认地址
    getUserInfoAndAddress: function (callback) {
      var $this = this
      var addressId = 0
      if ($this.$route.query.chooseAddressId) {
        addressId = $this.$route.query.chooseAddressId
      }
      $this.MyRequest($this.ApiDoNameMember + 'Member/getUserInfoAndAddress', {addressId}, function (data) {
        if (data && data.memberAddress && data.memberAddress.id) {
          $this.memberAddress.id = data.memberAddress.id
          $this.memberAddress.name = data.memberAddress.name
          $this.memberAddress.province = data.memberAddress.province
          $this.memberAddress.city = data.memberAddress.city
          $this.memberAddress.county = data.memberAddress.county
          $this.memberAddress.mobile = data.memberAddress.mobile
          $this.memberAddress.address = data.memberAddress.address
          $this.memberAddress.isDefault = data.memberAddress.isDefault === 1
        }
        if (data && data.userInfo) {
          $this.userInfo=data.userInfo
        }
        if (!$this.userInfo.isVip){
          $this.userInfo.level=0
        }
        $this.levelMap=data.levelMap
        $this.isGetAddress=true
        callback()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    calcAllPrice:function () {
      let $this=this
      var priceDetail={
        productNums:0,
        productPrice:0,
        couponPrice:0,
        expressPrice:0,
        fullMinusPrice:0,
        vipDiscountPrice:0,
        price:0,
      }
      $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
        var priceItem=item.getPrice()
        priceDetail.productNums+=priceItem.productNums
        priceDetail.productPrice=(priceDetail.productPrice+priceItem.productPrice).toFixed(2)-0
        priceDetail.couponPrice=(priceDetail.couponPrice+priceItem.couponPrice).toFixed(2)-0
        priceDetail.expressPrice=(priceDetail.expressPrice+priceItem.expressPrice).toFixed(2)-0
        priceDetail.fullMinusPrice=(priceDetail.fullMinusPrice+priceItem.fullMinusPrice).toFixed(2)-0
        priceDetail.vipDiscountPrice=(priceDetail.vipDiscountPrice+priceItem.vipDiscountPrice).toFixed(2)-0
        // console.log('item',item)
      })

      priceDetail.price=(priceDetail.productPrice+priceDetail.expressPrice).toFixed(2)-0
      priceDetail.price=(priceDetail.price-priceDetail.couponPrice).toFixed(2)-0
      priceDetail.price=(priceDetail.price-priceDetail.fullMinusPrice).toFixed(2)-0
      priceDetail.price=(priceDetail.price-priceDetail.vipDiscountPrice).toFixed(2)-0
      $this.priceDetail=priceDetail
      $this.$forceUpdate()
    },
    initData:function (callback) {
      var selectDataListString = localStorage.getItem('selectProductDataList');
      let $this=this
      if (selectDataListString && selectDataListString.length>0){
        this.selectShopList=JSON.parse(selectDataListString)
        this.getUserInfoAndAddress(function () {
          $this.getShopsInfo(function () {
            $this.getCouponList(function () {
              $this.getClassifyMap(function () {
                $this.isGetShopList=true
                callback()
                $this.$forceUpdate()
                // console.log('this.getAbleCouponList',$this.getAbleCouponList(11,285,100))
              })
            })
          })
        })
        // console.log('this.selectShopList',this.selectShopList)
      }
    },

    // 获取店铺信息
    getShopsInfo:function (callback) {
      var shopIdList=[]
      this.selectShopList.forEach(function (item, index) {
        shopIdList.push(item.shop.id)
      })
      let $this=this
      $this.MyRequest($this.ApiDoNameMember + 'Shop/getList', {ids: shopIdList.join(',')}, function (data) {
        data.list.forEach(function (_shop, _index) {
          $this.selectShopList.forEach(function (item, index) {
            if (item.shop.id===_shop.id){
              $this.selectShopList[index].shop=_shop
            }
          })
        })
        $this.$forceUpdate()
        callback()
      })
    },

    // 获取优惠券列表
    getCouponList: function (callback) {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Member/getCouponList', {
        status: 1,
        size:50
      }, function (data) {
        $this.couponList = data.list
        callback()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },

    // 获取优惠券列表
    getClassifyMap: function (callback) {
      let $this = this
      var classifyIdList=[]
      $this.selectShopList.forEach(function (item, index) {
        item.productList.forEach(function (stock, _index) {
          classifyIdList.push(stock.classifyId)
        })
      })
      $this.MyRequest($this.ApiDoNameMember + 'ShopProduct/getClassifyIdMap', {
        classifyIdList: classifyIdList.join(',')
      }, function (classifyIdMapList) {
        $this.classifyIdMapList=classifyIdMapList
        // console.log('classifyIdMapList',classifyIdMapList)
        callback()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },

    getCLassifyRootId:function (id) {
      var rootId=-1
      this.classifyIdMapList.forEach(function (value, index) {
        if (value.id===id){
          rootId=value.rootId
        }
      })
      return rootId
    },

    // 单个店铺-获取-可用优惠券
    getAbleCouponList:function (shopId,classifyId,producePrice) {
      var arr=[]
      let $this=this
      var cLassifyRootId = this.getCLassifyRootId(classifyId);
      $this.couponList.forEach(function (item, index) {
        if (item.shopId===shopId || item.shopId===0){
          if (item.productClassifyId===0 || cLassifyRootId===item.productClassifyId){
            if (item.fullMoney<=producePrice){
              if (!item.isUsed || item.isUsed===shopId){
                arr.push(item)
              }
              // console.log('item',JSON.stringify(item))
            }
          }
        }
      })
      console.log('arr',arr)
      return arr
    },


    setCouponUsed:function (id,shopId,isUsed) {
      let $this=this
      $this.couponList.forEach(function (item, index) {
        if (id===item.id){
          if (isUsed){
            $this.$set($this.couponList[index],'isUsed',shopId)
          }else{
            $this.$set($this.couponList[index],'isUsed',0)
          }
        }
      })

      if (isUsed){
        $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
          if (item.shop.id!==shopId){
            item.getCoupon()
          }
        })
      }
      $this.calcAllPrice()
    },

    // 检查是否需要地址
    checkNeedAddress:function () {
      let $this=this
      var needAddress=false
      $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
        if (item.sendType!==2){
          needAddress=true
        }
      })
      $this.needAddress=needAddress
      $this.$forceUpdate()
    },

    // 批次提交
    submit:function () {
      let $this=this
      var formList=[]
      $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
        var form=item.getSubmit()
        if (!form){
          return
        }
        formList.push(form)
      })
      if (this.needAddress && !this.memberAddress.id){
        return this.$message.error('请先选择 收货地址')
      }
      var form={
        addressId:this.memberAddress.id,
        payType:this.payType,
        shopProductString:JSON.stringify(formList)
      }
      $this.loading=true
      $this.MyRequest($this.ApiDoNameMember + 'Order/submitMore', form,function (prePayData) {
        $this.loading=false
        $this.clearCartCache()
        // 余额支付
        if ($this.payType===0){
          $this.$message.success('支付成功')
          $this.goToSuccess()
        }else{
          // 其他支付类型
          $this.execusePay(prePayData)
        }
      },function (res) {
        $this.$message.error(res.message)
        $this.loading=false
      })
    },

    // 执行支付-微信,支付宝,对公支付
    execusePay:function (prePayData) {
      let $this=this
      if (typeof plus==='undefined' && ($this.payType===1 || $this.payType===2)){
        return $this.$message.warning('H5 暂不支持【微信，支付宝】支付');
      }
      localStorage.setItem("PaySuccessOrderData",JSON.stringify(this.getProductData()))
      switch (this.payType) {
        // 微信支付
        case 1:
          $this.pay('wxpay',{
            appid: prePayData.appid,
            prepayid: prePayData.prepayid,
            partnerid: prePayData.partnerid,
            noncestr: prePayData.noncestr,
            timestamp: prePayData.timestamp,
            package: prePayData.package,
            sign: prePayData.sign
          },function () {
            $this.$message.success('支付成功')
            $this.goToSuccess()
            $this.$forceUpdate()
          },function () {
            $this.$message.info('未完成支付')
            $this.$router.push({
              name: 'OrderList'
            })
          })
          break
        // 支付宝支付
        case 2:
          $this.pay('alipay',prePayData,function () {
            $this.$message.success('支付成功')
            $this.goToSuccess()
            $this.$forceUpdate()
          },function () {
            $this.$message.info('未完成支付')
            $this.$router.push({
              name: 'OrderList'
            })
          })
          break
        // 对公支付
        case 3:
          localStorage.setItem("PayMoreOrderId",prePayData)
          localStorage.setItem("PaySuccessOrderData",JSON.stringify(this.getProductData()))
          // 附加商品,价格信息至参数
          this.$router.push({
            name: 'EnterprisePayInfo',
            query: {
              type: 'orderMore',
            }
          })
          return
          break
      }
    },

    // 获取提交商品
    getProductData:function () {
      let $this=this
      var productList=[]
      $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
        item.productList.forEach(function (value,index) {
          if (productList.length<4){
            productList.push({
              shopProductName:value.shopProductName,
              model:value.model,
              nums:value.nums,
            })
          }
        })
      })
      return {
        price:this.priceDetail.price,
        payType:this.payType,
        orderNo:$this.$refs['confirm-order-more-shop-item'].length+' 条订单合并付款',
        productList:productList
      };
    },

    // 跳转支付成功页面
    goToSuccess: function  () {
      localStorage.setItem("PaySuccessOrderData",JSON.stringify(this.getProductData()))
      this.$router.push({
        name: 'PaySuccess',
        query: {
          type: 'orderMore',
        }
      })
    },

    // 清空购物车
    clearCartCache:function () {
      let $this=this
      var tmpStockIdList=[]
      $this.$refs['confirm-order-more-shop-item'].forEach(function (item, index) {
        item.productList.forEach(function (value,index) {
          tmpStockIdList.push(value.id)
        })
      })

      $this.bus.$emit('CartUtilCallBus','deleteCartProductStockItem',{
        id:tmpStockIdList.join(','),
        nums:0,
      },function () {})
    }


  }
}
</script>

<style scoped>

</style>
